package com.shsc.example.project;

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;

public class MusicService extends Service {
    private MediaPlayer player;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //这里只执行一次，用于准备播放器
        player = new MediaPlayer();
        try {
            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.music);
            player.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
                    file.getLength());
            //准备资源
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("Service", "准备播放音乐onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("Service", "绑定服务onBind");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("Service", "解绑服务onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.e("Service", "onDestroy");
        super.onDestroy();
        player.pause();
        player.release();
    }

    //该方法包含关于歌曲的操作
    public class MyBinder extends Binder {

        //判断是否处于播放状态
        public boolean isPlaying(){
            return player.isPlaying();
        }

        //播放或暂停歌曲
        public void play() {
            if (player.isPlaying()) {
                player.pause();
            } else {
                player.start();
            }
            Log.e("Service", "播放/暂停音乐");
        }
    }
}